package com.game.service.impl;

import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;

import com.game.dao.IAccessTokenDao;
import com.game.dao.IUserDao;
import com.game.pojo.AccessToken;
import com.game.pojo.User;
import com.game.service.IUserService;
import com.game.util.AccessTokenUtil;
import com.game.util.HttpUtils;
import com.game.util.UserUtils;
@Stateless
@Local(IUserService.class)
public class UserService implements IUserService {
	@Inject private IUserDao userDao;
	@Inject private IAccessTokenDao accessTokenDao;
	
	/**
	 * 根据openId从微信服务器获取用户信息，并且保存到数据库
	 */
	@Override
	public User getUserInfo(String openId) {
		//调用高级接口获取已关注用户的信息
		//先判断数据库token是否过期，如果过期重新获取
		
		//如果超过2小时，就重新获取
		if(isExpired()){
			AccessToken accessToken = AccessTokenUtil.getAccessToken();
			//保存到数据库
			accessTokenDao.saveAccessToken(accessToken);
		}
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		url = url.replace("ACCESS_TOKEN", accessTokenDao.getAccessToken().getToken());
		url = url.replace("OPENID", openId);
		//调用高级接口返回的响应
		String respString = HttpUtils.getHttp(url);
		//调用用户工具类获取用户信息
		User user = UserUtils.jsonToUser(respString);
		//把新关注的用户存到数据库
		userDao.saveUser(user);
		return user;
	}
	
	/**
	 * 获取公众号关注列表
	 */
	@Override
	public List<User> getUserList() {
		
		//先判断数据库token是否过期，如果过期重新获取
		
		//如果超过2小时，就重新获取
		if(isExpired()){
			AccessToken accessToken = AccessTokenUtil.getAccessToken();
			//保存到数据库
			accessTokenDao.saveAccessToken(accessToken);
		}
		
		String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=";
		url = url.replace("ACCESS_TOKEN", accessTokenDao.getAccessToken().getToken());
		//调用高级接口返回的响应
		String respString = HttpUtils.getHttp(url);
		//调用用户工具类获取用户openId集合
		List<String> openIdList = UserUtils.jsonToUserList(respString);
		//遍历集合，保存到数据库
		for (String openId : openIdList) {
			getUserInfo(openId);
		}
		return null;
	}
	
	public boolean isExpired(){
		long createTime = accessTokenDao.getAccessToken().getCreateTime();
		//计算获取了多长时间
		long time = new Date().getTime() - createTime;
		//2个小时
		long twoHours = 1000 * 60 * 60 * 2;
		return time >= twoHours;
	}
}
